
//////////Need to modify for each application////////////////
var APP_ID = 34839;
//var SERVER_NAME = "http://harnivorouspartner.appspot.com/";
var SERVER_NAME = "http://facewords.appspot.com/";
/////////////////////////////////////////////////////////////


var userAgent = "";
var contentsPage = ["voicePage", "searchPage", "favoritePage", "rankingPage", "diagnosisPage"];
var contentsNav = ["voiceNav", "searchNav", "favoriteNav", "rankingNav", "diagnosisNav"];
var isViewedPage = [true, false, false, false, false];
var TEXTAREA_DIV_NAME = "voiceText";
var VOICE_PAGE_NAME = "voicePage";
var FAVORITE_PAGE_NAME = "favoritePage";
var FAVORITE_MAX = 30;
var userID = "";
var faceUpdate = false;

function showPicWord(divname){
    picWordArea = document.getElementById(divname);
    if (picWordArea.innerHTML == "") {
        loadPicWords(divname);
    }

    switchVisibility(divname);
    
}

function loadPicWords(divname){
    html = "選択された絵文字はプレビューでは文字コードとして表示されますが、投稿時に絵文字に変換されます。<br/><span id=\"picWords\">";
    for (i = 1; i <= 246; i++) {
        html = html + "<span class=\"picWord\"><a onclick=\"pickPicWord(" + i + ",'" + divname + "')\" ><img src=\"http://img.mixi.net/img/emoji/" + i + ".gif\" /></a></span>";
    }
    html = html + "<input class=\"button closeButton\" type=\"button\" onclick=\"switchVisibility('picWordArea')\" value=\"閉じる\"/></span>"
    document.getElementById(divname).innerHTML = html;
}


function showAddHome(divname){
    addHomeArea = document.getElementById(divname);
    if (addHomeArea.innerHTML == "") {
        loadAddHome(divname);
    }
    switchVisibility(divname);
    
}

function loadAddHome(divname){
    html = "画面下部のアイコンをクリック。<br/><img src=\"" + SERVER_NAME + "html/homeFooterS.JPG\" /><br/>ホーム画面へ追加を選択してね。<br/><img src=\"" + SERVER_NAME + "html/addHomeS.JPG\" /><br/>これで<img src=\"" + SERVER_NAME + "html/webIconS.JPG\" />がスマートフォンのホームに追加されるから次回からの起動が簡単♪<br/><input class=\"button closeButton\" type=\"button\" onclick=\"switchVisibility('homeAddArea')\" value=\"閉じる\"/>"
    document.getElementById(divname).innerHTML = html;
}

function pickPicWord(gifID, divname){
    textAreaObj = document.getElementById(TEXTAREA_DIV_NAME);
    textAreaObj.value = textAreaObj.value + "[m:" + gifID + "]";
    switchVisibility(divname);
    calculate(textAreaObj);
}

function switchVisibility(divname){
    if (document.getElementById(divname).style.display == "none") {
        document.getElementById(divname).style.display = "";
    }
    else {
        document.getElementById(divname).style.display = "none";
    }
        moveToTop();
}

function send_get(divname, url){
    getRequest(divname, url);
    // mixiGetRequest(divname, url);
}

function movePage2(divname, url, refresh){
    if (userID == "") {
        //getUserInfo();
        // userID = getUserInfo2();
        getUserID();
    }
    location.hash = divname;
    contentsID = divname.replace("Page", "Contents");
    contents = document.getElementById(contentsID).innerHTML;
    if (refresh || contents == "") {
        send_get(contentsID, url + "?userID=" + userID);
    }
    
    navID = divname.replace("Page", "Nav");
    resetNavButtion(navID);
}

function movePage(divname, url, refresh){
    if (userID == "") {
        //getUserInfo();
        // userID = getUserInfo2();
        getUserID();
    }
    //    location.hash = divname;
    
    contentsID = divname.replace("Page", "Contents");
    contents = document.getElementById(contentsID).innerHTML;
    if (refresh || contents == "") {
        send_get(contentsID, url + "?userID=" + userID);
    }
    else 
        if ((divname == FAVORITE_PAGE_NAME) && faceUpdate) {
            send_get(contentsID, url + "?userID=" + userID);
            faceUpdate = false;
        }
    viewContents(divname);
    resetNav(divname);
}

function viewContents(pageName){
    for (i = 0; i < contentsPage.length; i++) {
        contentsID = contentsPage[i].replace("Page", "Contents");
        if (pageName == contentsPage[i]) {
            document.getElementById(contentsID).style.display = "";
        }
        else {
            document.getElementById(contentsID).style.display = "none";
        }
    }
}

function viewPage(pageName){
    for (i = 0; i < contentsPage.length; i++) {
        if (pageName == contentsPage[i]) {
            document.getElementById(contentsPage[i]).style.display = "";
        }
        else {
            document.getElementById(contentsPage[i]).style.display = "none";
        }
    }
}

function resetNav(pageName){

    for (i = 0; i < contentsPage.length; i++) {
        navID = contentsPage[i].replace("Page", "Nav");
        if (pageName == contentsPage[i]) {
            document.getElementById(navID).className = "navActive";
        }
        else {
            document.getElementById(navID).className = "navInactive";
        }
        
    }
    
}


function getUserID(){

    userID = document.getElementById("userID").value;
    
}

function resetNavButtion(activeNavName){
    navID = divname.replace("Page", "Nav");
    for (i = 0; i < contentsPage.length; i++) {
        candNavs = document.getElementsByClassName(contentsNav[i]);
        
        if (activeNavName == contentsNav[i]) {
            // active navi
            clsName = "ui-btn ui-btn-icon-top ui-btn-active ui-btn-up-a" + " " + contentsNav[i];
        }
        else {
            // inactive navi
            clsName = "ui-btn ui-btn-icon-top ui-btn-up-a" + " " + contentsNav[i];
        }
        
        for (j = 0; j < candNavs.length; j++) {
            candNavs[j].className = clsName;
        }
    }
    
}



function getRequest(divname, url){
    httpRequest = false;
    if (window.XMLHttpRequest) {
        // Firefox, Opera など
        httpRequest = new XMLHttpRequest();
        httpRequest.overrideMimeType('text/xml');
    }
    else 
        if (window.ActiveXObject) {
            // IE
            try {
                httpRequest = new ActiveXObject('Msxml2.XMLHTTP');
            } 
            catch (e) {
                httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
            }
        }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function(){
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            if (divname != '') {
                if (httpRequest.responseText != "") {
                    document.getElementById(divname).innerHTML = httpRequest.responseText;
                    //            document.getElementById(divname).innerHTML = document.getElementById(divname).innerHTML + httpRequest.responseText;
                }
            }
        }
    }
    httpRequest.send("");
}

function mixiGetRequest(divname, url){
    url = SERVER_NAME + url;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    gadgets.io.makeRequest(url, function(response){
        /// no action
        if (response.data) {
            document.getElementById(divname).innerHTML = response.data;
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。しばらく時間をおいてからリロードしてください。");
        }
    }, params);
}


function backToTop(){
    //    $('html').animate({
    //       scrollTop: 0
    //    }, 'fast');
    //   return false;
    window.scrollTo(0, 0);
}

function loadMainContents(){
    //    getUserInfo();
    send_get("mainContents", "init");
}

////////////////////////////////////


function movePageOrg(divname, url){
    userID = getUserInfo2();
    for (i = 0; i < contentsPage.length; i++) {
        if (divname == contentsPage[i]) {
            // to refresh favoritePage everytime
            if (divname == "favoritePage") {
                isViewedPage[i] = false;
                document.getElementById(divname).innerHTML = "";
            }
            if (isViewedPage[i] == false) {
                loadContents(divname, url + "?userID=" + userID, false);
                isViewedPage[i] = true;
            }
            else {
                document.getElementById(contentsPage[i]).style.display = "";
            }
        }
        else {
            document.getElementById(contentsPage[i]).style.display = "none";
        }
    }
    navID = divname.replace("Page", "Nav");
    resetNavButtion(navID);
}

function getUserInfo2(){
    return "abcdefg";
}




function switchFavorite(divname, url){
    element = document.getElementById(divname);
    oldClassName = element.className
    newClassName = "favoriteTrue";
    if (element.className.indexOf("favoriteTrue") != -1) {
        newClassName = oldClassName.replace("favoriteTrue", "favoriteFalse");
    }
    else {
        newClassName = oldClassName.replace("favoriteFalse", "favoriteTrue");
    }
    elements = document.getElementsByClassName(oldClassName);
    for (i = 0; i < elements.length; i++) {
        elements[i].className = newClassName;
    }
    send_get(divname, url);
    
}


function request_favorite(divname, url){
    httpRequest = false;
    if (window.XMLHttpRequest) {
        // Firefox, Opera など
        httpRequest = new XMLHttpRequest();
        httpRequest.overrideMimeType('text/xml');
    }
    else 
        if (window.ActiveXObject) {
            // IE
            try {
                httpRequest = new ActiveXObject('Msxml2.XMLHTTP');
            } 
            catch (e) {
                httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
            }
        }
    
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function(){
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            if (divname != '') {
                if (httpRequest.responseText == "") {
                    element = document.getElementById(divname);
                    oldClassName = element.className
                    newClassName = "favoriteTrue";
                    if (element.className.indexOf("favoriteTrue") != -1) {
                        newClassName = oldClassName.replace("favoriteTrue", "favoriteFalse");
                    }
                    else {
                        newClassName = oldClassName.replace("favoriteFalse", "favoriteTrue");
                    }
                    elements = document.getElementsByClassName(oldClassName);
                    v = elements.length;
                    i = 0;
                    while (i < v) {
                        elements[0].className = newClassName;
                        i++;
                    }
                    faceUpdate = true;
                }
                else {
                    /*
                     jConfirm('確認ダイアログ', '確認ダイアログのタイトル', function(r){
                     if (r == true) {
                     movePage('favoritePage', 'favoritePage/0', true);
                     resetNav('favoritePage');
                     moveToTop();
                     }
                     });
                     */
                    if (window.confirm('お気に入りの登録は' + FAVORITE_MAX + '個までです。\nお気に入りを編集しますか？')) {
                        movePage('favoritePage', 'favoritePage/0', true);
                        resetNav('favoritePage');
                        moveToTop();
                    }
                    else {
                        // cancel action
                    }
                    
                }
            }
        }
    }
    httpRequest.send("");
}

function pickFaceWord(faceword, url){
    send_get('', url);
    movePage("voicePage");
    textAreaObj = document.getElementById(TEXTAREA_DIV_NAME);
    textAreaObj.value = textAreaObj.value + document.getElementById(faceword).textContent;
    calculate(textAreaObj);
    //	location.hash="page";
    moveToTop();
}


function resetNavButtion2(activeNavName){
    for (i = 0; i < contentsNav.length; i++) {
        if (activeNavName == contentsNav[i]) {
            document.getElementById(contentsNav[i]).className = "ui-btn ui-btn-icon-top ui-btn-active ui-btn-up-a";
            
        }
        else {
            document.getElementById(contentsNav[i]).className = "ui-btn ui-btn-icon-top ui-btn-up-a";
            
        }
    }
    
}

function resetText(){
    textAreaObj = document.getElementById(TEXTAREA_DIV_NAME);
    textAreaObj.value = "";
    calculate(textAreaObj);
}

function loadMoreContents(divname, url, insertDivname){
    send_get(divname, url);
    
    
}

function loadMoreContents(divname, url, isItem){
    send_get(divname, url);
    
    if (isItem) {
    
        if (document.getElementById(divname).style.display == "none") {
            document.getElementById(divname).style.display = "";
        }
        else {
            document.getElementById(divname).style.display = "none";
        }
        
    }
    else {
        document.getElementById(divname).style.display = "";
        
    }
}

function loadContents(divname, url, isItem){
    if (document.getElementById(divname).innerHTML == "") {
        send_get(divname, url);
        document.getElementById(divname).style.display = "none";
    }
    
    if (isItem) {
        secName = divname.replace("Area", "Section");
        if (document.getElementById(divname).style.display == "none") {
            document.getElementById(divname).style.display = "";
            
            document.getElementById(secName).innerHTML = "－";
        }
        else {
            document.getElementById(divname).style.display = "none";
            document.getElementById(secName).innerHTML = "＋";
        }
        
    }
    else {
        document.getElementById(divname).style.display = "";
        
        
    }
}


function categoryRequest(divname, mCategoryID){
    var REQUEST_URL = SERVER_NAME + "category/" + mCategoryID;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    gadgets.io.makeRequest(REQUEST_URL, function(response){
        /// no action
        if (response.data) {
            document.getElementById(divname).innerHTML = response.data;
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。しばらく時間をおいてからリロードしてください。");
        }
    }, params);
    
}

function staticPageRequest(pageID){
    var REQUEST_URL = SERVER_NAME + pageID;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    gadgets.io.makeRequest(REQUEST_URL, function(response){
        /// no action
        if (response.data) {
            document.getElementById(pageID).innerHTML = response.data;
            
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。しばらく時間をおいてからリロードしてください。");
        }
    }, params);
}

function createTopPage(){

    var req = opensocial.newDataRequest();
    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.HAS_APP];
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), "viewer");
    req.send(function(data){
        if (!data.hadError()) {
            var item = data.get("viewer");
            if (item.hadError()) {
                var code = item.getErrorCode();
                // error logic                
            }
            else {
            
                var viewer = item.getData();
                hasApp = viewer.getField(opensocial.Person.Field.HAS_APP);
                // if viewer doesn't have application, move to application registration page
                if (hasApp == "false") {
                    location.href = "http://mixi.jp/view_appli.pl?id=" + APP_ID;
                }
                else {
                    makeTopPage();
                }
            }
        }
    });
}


function makeTopPage(){

    var url = SERVER_NAME + TOP_POST;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    
    gadgets.io.makeRequest(url, function(response){
        if (response.data) {
        
            document.getElementById("mainContents").innerHTML = response.data;
            gameTime = 0;
            //  getUserInfo();
        
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。しばらく時間をおいてからリロードしてください。");
        }
    }, params);
}

function createGamePage(){
    var REQUEST_URL = SERVER_NAME + GAME_POST;
    var params = {};
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    var gender;
    //detect gender
    if (gameTime == 0) {
        if (document.getElementsByName("gender")[0].checked) {
            gender = "0";
        }
        else {
            gender = "1";
        }
    }
    else {
        gender = document.getElementById("gender").value;
    }
    
    
    var post_data = {
        questionNum: document.getElementById("questionNum").value,
        sessionID: document.getElementById("sessionID").value,
        nickname: document.getElementById("nickname").value,
        username: document.getElementById("username").value,
        gender: gender
    };
    if (gameTime > 0) {
        var answer = checkAnswer();
        post_data["answer"] = answer;
    }
    params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(post_data);
    
    gadgets.io.makeRequest(REQUEST_URL, function(response){
        /// no action
        if (response.data) {
        
            document.getElementById("mainContents").innerHTML = response.data;
            gameTime = gameTime + 1;
            
            if (gameTime > GAME_TIME) {
                document.getElementById("mainContents").style.backgroundImage = 'url("' + SERVER_NAME + RESULT_IMG_POST + AGENT_POST + '")';
            }
            else {
                document.getElementById("mainContents").style.backgroundImage = 'url("' + SERVER_NAME + GAME_IMG_POST + AGENT_POST + '")';
                
            }
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。しばらく時間をおいてからリロードしてください。");
        }
    }, params);
}

function checkAnswer(){
    for (i = 0; i < ANSWER_NUM; i++) {
        if (document.getElementsByName("answer")[i].checked) {
            return String(i);
        }
    }
}

function getUserInfo(){
    var req = opensocial.newDataRequest();
    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.HAS_APP];
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), "viewer");
    req.send(function(data){
        if (!data.hadError()) {
            var item = data.get("viewer");
            if (item.hadError()) {
                var code = item.getErrorCode();
                // error logic                
            }
            else {
                var viewer = data.get("viewer").getData();
                username = viewer.getDisplayName();
                userID = viewer.getId();
                //     document.getElementById("nicknameArea").innerHTML = nickname + "さん";
                //     document.getElementById("nickname").value = nickname;
                hasApp = viewer.getField(opensocial.Person.Field.HAS_APP);
                // if viewer doesn't have application, move to application registration page
                if (hasApp == "false") {
                    location.href = "http://mixi.jp/view_appli.pl?id=" + APP_ID;
                }
            }
        }
    });
}




/**
 *  refer to http://developer.mixi.co.jp/appli/spec/pc/invite_appli
 */
function inviteFriends(){
    //var params = {};
    //params[opensocial.IdSpec.Field.USER_ID] = inviteFriendIDs;
    //var recipients = opensocial.newIdSpec(params);
    //opensocial.requestShareApp(recipients, null, function(response){
    opensocial.requestShareApp("VIEWER_FRIENDS", null, function(response){
        if (response.hadError()) {
            var errCode = response.getErrorCode();
        }
        else {
            var recipientIds = response.getData()["recipientIds"];
        }
    });
}

function moveToTop(){
    location.href = "#pageAreaTop";
}

/**
 * refer to http://developer.mixi.co.jp/appli/spec/pc/send_voice
 * @param {Object} index
 */
function faceVoice(){
    voiceText = "";
    voiceText = document.getElementById(TEXTAREA_DIV_NAME).value;
    doVoice(voiceText);
}

function diagnosisVoice(){
    voiceText = "";
    voiceText = "あなたの顔文字傾向:" + document.getElementById("levelText").innerHTML+"。";
    voiceText = voiceText + " " + document.getElementById("diagnosisText").innerHTML;
    doVoice(voiceText);
}

function doVoice(voiceText){
    var params = {};
    // When you want to add URL in voice, please 
    params[mixi.Status.Field.URL] = "http://mixi.jp/view_appli.pl?id=" + APP_ID + "&appParams=";
    params[mixi.Status.Field.MOBILE_URL] = "http://ma.mixi.net/" + APP_ID + "/?url=";
    params[mixi.Status.Field.TOUCH_URL] = "http://mixi.jp/view_appli.pl?id=" + APP_ID + "&appParams=";
    mixi.requestUpdateStatus(voiceText, function(response){
        if (response.hadError()) {
            var code = response.getErrorCode();
            var msg = response.getErrorMessage();
            
        }
        else {
            //    movePage("", "init&userID=" + userID, true);
        }
    }, params);
}


